﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.Goods;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.DbHelpers;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business
{
    public class Shop_CartBusiness : BaseBusiness<Shop_Cart>, IShop_CartBusiness, ITransientDependency
    {
        private readonly IOperator _Operator;

        public Shop_CartBusiness(IDbAccessor db, IOperator Operators)
            : base(db)
        {
            _Operator = Operators;
        }

        #region 外部接口

        public async Task<PageResult<Shop_Cart>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Shop_Cart>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Shop_Cart, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<Shop_Cart> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(Shop_Cart data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Shop_Cart data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        #region 购物车前台接口

        /// <summary>
        /// 获取购物车商品
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Shop_CartDtos> GetShopCart(PageInput<ShopCartd> input)
        {
            try
            {
                var shopCartd = input.Search;
                Expression<Func<BTB_Goods, bool>> expression = k => true;

                if (shopCartd.ishot.HasValue)
                {
                    expression = k => k.IsHot == true;
                }

                var res = await Db.GetIQueryable<Shop_Cart>().Where(p => p.CreatorId.Equals(_Operator.UserId) && p.Deleted == false).ToListAsync();

                List<Shop_CartDto> cartDtos = new List<Shop_CartDto>();
                foreach (var item in res)
                {
                    var wheres = LinqHelper.True<BTB_GoodsSpecificationsItem>();

                    Expression<Func<BTB_GoodsSpecificationsItem, bool>> expressionone = s => s.GoodsSpecificationsItemID.Equals(item.Products_Id);
                    wheres = wheres.And(expressionone);
                    if (shopCartd.Invort.HasValue)
                    {
                        Expression<Func<BTB_GoodsSpecificationsItem, bool>> expressiontwo = s => s.Inventory <= 0;

                        wheres = wheres.And(expressiontwo);
                    }

                    var p = from s in Db.GetIQueryable<BTB_GoodsSpecificationsItem>().Where(wheres)
                            join k in Db.GetIQueryable<BTB_Goods>().Where(expression) on s.GoodsID equals k.ID
                            select new GoodsDtom
                            {
                                ID = k.ID,
                                CreateTime = k.CreateTime,
                                CreatorId = k.CreatorId,
                                Supplierid = k.Supplierid,
                                GoodsDescribe = k.GoodsDescribe,
                                GoodsName = k.GoodsName,
                                GoodsPic = k.GoodsPic,
                                ItemPic =s.Pic,
                                GoodsPrice = k.GoodsPrices,
                                GoodsTypeId = k.GoodsTypeId,
                                Details = k.Details,
                                IsHot = k.IsHot,
                                _GoodsSpecificationsItem = new GoodsItemDto
                                {
                                    GoodsSpecificationsItemID = s.GoodsSpecificationsItemID,
                                    CreateTime = s.CreateTime,
                                    Specs = s.GoodsSpecifications,
                                    Inventory = s.Inventory,
                                    Price = s.Price,
                                    // BTB_GoodsPic = Db.GetIQueryable<BTB_GoodsPic>(true).Where(u => u.GoodsItem_ID.Equals(s.GoodsSpecificationsItemID)).ToList()
                                }
                            };

                    var ps = p?.ToList();
                    decimal? Price = ps?.FirstOrDefault()?._GoodsSpecificationsItem?.Price;
                    if (ps.Count > 0)
                    {
                        var s = ps.FirstOrDefault();
                        Shop_CartDto shop_CartDto = new Shop_CartDto
                        {
                            Id = item.Id,
                            CreatorId = item.CreatorId,
                            CreateTime = item.CreateTime,
                            Deleted = item.Deleted,

                            Products_Id = item.Products_Id,

                            GoodsPic = s.GoodsPic,
                            ItemPic = s.ItemPic,

                            SumPrice = Price,
                            TotalPrice = Price * item?.ShopNum,
                            ShopNum = item.ShopNum,
                            Stock = s?._GoodsSpecificationsItem?.Inventory == null ? 0 : s?._GoodsSpecificationsItem?.Inventory,
                            _Goods = s
                        };
                        cartDtos.Add(shop_CartDto);
                    }
                }

                int total = cartDtos.Count;
                int sCount = input.PageRows * (input.PageIndex - 1);
                var gList = cartDtos.OrderByDescending(x => x.Id).Skip(sCount).Take(input.PageRows).ToList();

                

                Shop_CartDtos _CartDtos = new Shop_CartDtos
                {
                    Total = total,
                    Data = gList,
                    sumPrice = gList.Sum(p => p.TotalPrice)
                };

                return _CartDtos;
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }

        public async Task AddDataTwoAsync(List<Shop_Cart> data)
        {
            List<Shop_Cart> sgList = new List<Shop_Cart>();
            List<Shop_Cart> sguList = new List<Shop_Cart>();
            foreach (var item in data)
            {
                var RESULT = await Db.GetIQueryable<BTB_GoodsSpecificationsItem>().SingleOrDefaultAsync(p => p.GoodsSpecificationsItemID.Equals(item.Products_Id));

                if (!RESULT.IsNullOrEmpty() && RESULT.Inventory != 0)
                {
                    var gMdoel = Db.GetEntity<BTB_Goods>(RESULT.GoodsID);
                    if (gMdoel.IsPointGoods == true)
                    {
                        throw new BusException("积分商品无法加入购物车，请重试！");
                    }

                    var res = Db.GetIQueryable<Shop_Cart>().FirstOrDefault(s => s.CreatorId.Equals(_Operator.UserId) && s.Products_Id.Equals(item.Products_Id) && s.Deleted != true);
                    if (res != null)
                    {
                        Shop_Cart dModel = res;
                        if (item.ShopNum.HasValue && item.ShopNum > 0)
                        {
                            dModel.ShopNum = dModel.ShopNum + item.ShopNum;
                        }
                        else
                        {
                            dModel.ShopNum = dModel.ShopNum + 1;
                        }
                        sguList.Add(dModel);
                    }
                    else
                    {
                        Shop_Cart _Cart = new Shop_Cart
                        {
                            Id = IdHelper.GetId(),
                            CreatorId = _Operator.UserId,
                            CreateTime = DateTime.Now,
                            Cart_Start = "0",
                            Deleted = false,
                            Products_Id = item.Products_Id,
                            // SumPrice = item.SumPrice
                        };

                        _Cart.ShopNum = item.ShopNum == null ? 1 : item.ShopNum;
                        sgList.Add(_Cart);
                    }
                }
                else
                {
                    throw new BusException("加入失败，库存不足！");
                }
            }

            if (sguList.Count > 0)
            {
                await Db.UpdateAsync(sguList);
            }

            if (sgList.Count > 0)
            {
                await Db.InsertAsync(sgList);
            }
           
        }

        public async Task UpdateNum(ShopCartNum cartNum)
        {
            if (cartNum.Num > 0)
            {
                decimal Price = cartNum.Price * cartNum.Num;
                string sql = $"UPDATE Shop_Cart SET ShopNum = '{cartNum.Num}',SumPrice='{Price}' WHERE Id = '{cartNum.Id}'";
                var qs = DbHelperSQL.ExecuteSql(sql);
            }
        }

        #endregion 购物车前台接口

        #endregion 外部接口
    }
}